package ro.gateway.aida.fnd;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.admin.PropertyListDB;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.servlet.Constants;
import ro.gateway.aida.srv.EditorServlet;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.obj.db.OrganizationDB;


/**
 * <p>Title: Romanian AIDA</p>
 * <p>Description: :D application</p>
 * <p>Copyright: Copyright (comparator) 2003</p>
 * <p>Company: Romania Development Gateway </p>
 *
 * @author Mihai Popoaei, mihai_popoaei@yahoo.com, smike@intellisource.ro
 * @version 1.0-* @version $Id: FundingItemEditorServlet.java,v 1.1 2004/10/24 23:37:14 mihaipostelnicu Exp $
 */
public class FundingItemEditorServlet extends EditorServlet {
	protected void other_action_performed(HttpServletRequest request,
								   HttpServletResponse response,
								   String action)
		 throws IOException, ServletException {
	}

	protected void start_editing(ServletContext application,
						    HttpServletRequest request,
						    HttpServletResponse response)
		 throws IOException, ServletException {
		super.start_editing(application, request, response);

		HttpSession session = request.getSession();
		Hashtable bean = (Hashtable) request.getAttribute(PNAME_BEAN);
		String key = (String) bean.get(PNAME_KEY);
		String action = (String) bean.get(PNAME_ACTION);

		String box = HttpUtils.getValidTrimedString(request, "box", null);
		if (box == null) {
			return;
		}
		Object obox = session.getAttribute(box);
		if ((obox == null) || (!(obox instanceof Hashtable))) {
			return;
		}
		Hashtable zabox = (Hashtable) obox;
		bean.put(PNAME_BOX, zabox.get(PNAME_BOX_LIST));
		bean.put(PNAME_ACTIVITY_ITEM, zabox.get(PNAME_BOX_ACTIVITY_ITEM));

		if (PV_ACTION_NEW.equals(action)) {
			FundingItem item = new FundingItem();
			bean.put(PNAME_BEAN, item);
		} else if (PV_ACTION_EDIT.equals(action)) {
			ArrayList items = (ArrayList) ((Hashtable) obox).get(PNAME_BOX_LIST);
			int index = HttpUtils.getInt(request, "index", -1);
			if (index == -1) {
				cancel(request, response);
				return;
			}

			FundingItem item = (FundingItem) items.get(index);
			bean.put(PNAME_BEAN, item);
		} else {
			cancel(request, response);
		}
	}

	protected void cancel(HttpServletRequest request,
					  HttpServletResponse response)
		 throws IOException, ServletException {

		String key = (String) request.getAttribute(PNAME_KEY);

		Hashtable beans = (Hashtable) request.getSession().getAttribute(getPNAME_BEANS());
		Hashtable bean = (Hashtable) request.getAttribute(PNAME_BEAN);

		if ((key == null) || (bean == null)) {
			response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED,
				 "bad[::] request");

			return;
		}

		beans.remove(key);
		request.setAttribute(PNAME_SCREEN, PV_SCREEN_CANCEL);
		request.getRequestDispatcher(JSP_PAGE).
			 forward(request, response);
		return;
	}

	protected void edit(HttpServletRequest request,
					HttpServletResponse response)
		 throws IOException, ServletException {

		request.setAttribute(PNAME_SCREEN, PV_SCR_EDIT);
		request.getRequestDispatcher(JSP_PAGE).
			 forward(request, response);
	}

	protected void save(ServletContext application,
					HttpServletRequest request,
					HttpServletResponse response)
		 throws IOException, ServletException {
	}

	protected void confirm(HttpServletRequest request,
					   HttpServletResponse response)
		 throws IOException, ServletException {
		ServletContext application = this.getServletContext();

		PersistenceToken pers_token = PersistenceManager.
			 tokenLookup(application);
		Hashtable services = (Hashtable) application.getAttribute(Constants.SERVICES);
		if (services == null) {
			System.err.println("services null... edit funding item");
			return;
		}
		PersistenceToken token = PersistenceManager.tokenLookup(application);

		Hashtable bean = (Hashtable) request.getAttribute(PNAME_BEAN);
		FundingItem item = (FundingItem) bean.get(PNAME_BEAN);
		String key = (String) request.getAttribute(EditorServlet.PNAME_KEY);

		item.setAmount(HttpUtils.getDouble(request, "amount", 0));
		item.setCurrency(HttpUtils.getValidTrimedString(request, "currency", null));
		try {
			item.setOrg(OrganizationDB.getManager(token).
				 getByID(HttpUtils.getLong(request, "org_id", -1)));
//                  item.setType( FundingTypePersMan.getManager(pers_token).
//                        getById( HttpUtils.getLong( request, "type_id", -1 ) ) );
//                  item.setStatus( FundingStatusPersMan.getManager(pers_token).
//                        getById( HttpUtils.getLong( request, "status_id", -1 ) ) );
			item.setStatus(PropertyListDB.getManager(token)
				 .getItemById(HttpUtils.getLong(request, "status_id", -1)));
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}

		String delyitems = HttpUtils.getValidTrimedString(request, "delyitems", null);
		String delcitems = HttpUtils.getValidTrimedString(request, "delcitems", null);
		String afteryedit = HttpUtils.getValidTrimedString(request, "afteryedit", null);
		String aftercedit = HttpUtils.getValidTrimedString(request, "aftercedit", null);
		if (delyitems != null) {
			String[] values = request.getParameterValues("y_item_idx");
			if (values != null) {
				java.util.Arrays.sort(values);
				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;
					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						item.getYearlyItems().remove(value);
					}
				}
			}

			response.sendRedirect("efnd?action=edit&key=" + key);
			return;
		} else if (delcitems != null) {
			String[] values = request.getParameterValues("c_item_idx");
			if (values != null) {
				java.util.Arrays.sort(values);
				for (int i = values.length - 1; i >= 0; i--) {
					int value = -1;
					try {
						value = Integer.parseInt(values[i]);
					} catch (NumberFormatException nfEx) {
					}

					if (value != -1) {
						item.getByCatItems().remove(value);
					}
				}
			}

			response.sendRedirect("efnd?action=edit&key=" + key);
			return;
		} else if (afteryedit != null) {
			response.sendRedirect("efnd?action=edit&key=" + key);
			return;
		} else if (aftercedit != null) {
			response.sendRedirect("efnd?action=edit&key=" + key);
			return;
		}

		if (!item.isValid()) {
			response.sendRedirect("efnd?err=true&action=edit&key=" + key);
			return;
		}

		if (PV_ACTION_NEW.equals(bean.get(PNAME_ACTION))) {
			ArrayList box = (ArrayList) bean.get(PNAME_BOX);
			box.add(item);
		}

		Hashtable beans = (Hashtable) request.getSession().getAttribute(getPNAME_BEANS());
		beans.remove(key);

		request.setAttribute(PNAME_SCREEN, PV_SCREEN_SAVED);
		request.getRequestDispatcher(JSP_PAGE).
			 forward(request, response);
		return;
	}

	public String getJSP_PAGE() {
		return JSP_PAGE;
	}

	public String getPNAME_BEANS() {
		return PNAME_BEANS;
	}

	private static final String JSP_PAGE = "/fnd/fnd_item_editor.jsp";
	public static final String PNAME_BEANS = "FND_EDITING_ITEMS";
	public static final String PNAME_FUNDING_ITEM = "FUNDING_ITEM";
	public static final String PNAME_ERRORS = "errors";
	public static final String PNAME_ACTIVITY_ITEM = "act_item";
	// arraylist din sesiune / bean in care sint itemurile pe care
	// le editez / creez
	public static final String PNAME_BOX = "thebox";
	public static final String PNAME_BOX_LIST = "item_list";
	public static final String PNAME_BOX_ACTIVITY_ITEM = "item_actitem";


	public static final String PV_SCREEN_CANCEL = "SCR_CANCEL";
	public static final String PV_SCREEN_SAVED = "SCR_SAVED";
}
